package com.ttt.adbgui.utils;

import java.io.*;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Objects;

public class CmdTask implements Runnable {
    private String command;
    private String dirPath;

    // 执行结果
    private BufferedReader br;

    private ArrayList<String> strings;

    public CmdTask(String command) {
        this.dirPath = "C:\\";
        this.command = "cmd.exe /c " + command;;
    }

    public ArrayList<String> startExecute(){
        run();
        if (Objects.nonNull(br)){
            return strings;
        }else {
            return null;
        }
    }

    @Override
    public void run() {
        Process process = null;
        int exitVal = 0;
        try {
            process = Runtime.getRuntime().exec(command, null, new File(dirPath));
            // Runtime.exec()创建的子进程公用父进程的流，不同平台上，父进程的stream buffer可能被打满导致子进程阻塞，从而永远无法返回。
            //针对这种情况，我们只需要将子进程的stream重定向出来即可。
            new RedirCmdStreamThread(process.getInputStream(), " ").start();
            new RedirCmdStreamThread(process.getErrorStream(), " ").start();

            exitVal = process.waitFor();
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }

        if (exitVal != 0) {
            throw new RuntimeException("cmd任务执行失败");
        }
    }

    class RedirCmdStreamThread extends Thread {
        InputStream is;
        String printType;

        RedirCmdStreamThread(InputStream is, String printType) {
            this.is = is;
            this.printType = printType;
        }

        public void run() {
            try {
                InputStreamReader isr = new InputStreamReader(is,Charset.forName("GBK"));
                strings = new ArrayList<>();
                br = new BufferedReader(isr);
                String line = null;
                while ((line = br.readLine()) != null) {
                    String temp = printType + ">" + line;
                    strings.add(temp);
                    System.out.println(temp);
                }

            } catch (IOException ioe) {
                ioe.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        String cmd = "adb";
        // new CmdTask(cmd).run();
        CmdTask cmdTask = new CmdTask(cmd);
        ArrayList<String> strings1 = cmdTask.startExecute();
        System.out.println(strings1);
    }
}
